package cn.wu.reggie.controller;


import cn.wu.reggie.common.R;
import cn.wu.reggie.entity.Employee;
import cn.wu.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("login")
    public R<Employee> login(@RequestBody Employee param, HttpSession session){
        // 1 调用service完成查询

        R<Employee> result = employeeService.login(param);

        // 2 如果登录成功 将用户信息id保存到session中
        if (result.getCode() == 1){
            session.setAttribute("employee",result.getData().getId());
        }

        // 3 返回r
        return result;
    }

    @PostMapping("logout")
    public R<Employee> logout(HttpSession session){
        //清除该用户的session
        session.invalidate();

        //返回r
        return R.success(null);
    }


    @PostMapping
    public R save(@RequestBody Employee employee,HttpSession session){
        // 获取session id
        Long userId = (Long) session.getAttribute("employee");

        // 2 给employee设置创建人和更新人
        employee.setCreateUser(userId);
        employee.setUpdateUser(userId);

        // 3 调用service完成保存操作
        return employeeService.save(employee);
    }



    @GetMapping("page")
    public R findByPage(@RequestParam("page") Integer pageNum,Integer pageSize,String name){
        return employeeService.findByPage(pageNum,pageSize,name);
    }

    @PutMapping
    public R update(@RequestBody Employee employee,HttpSession session){
        Long userId = (Long) session.getAttribute("employee");
        // 1 给用户对象设置更新人id
        employee.setUpdateUser(userId);

        // 2 调用service完成更新
        return R.success(employeeService.update(employee));
    }

    @GetMapping("{id}")
    public R findById(@PathVariable Long id){
        R<Employee> result = employeeService.findById(id);
        return result;
    }

}
